<?php

class Group_MemberController extends Zend_Controller_Action
{
	protected $_account = NULL;
	protected $_group = NULL;

	public function init()
	{
		parent::init();

		$this->_account = Account_Model_Session::getAccount();

		if ($this->_account != NULL) {
			$groupIdName = $this->_getParam('entity_idname');
			$this->_group = Group_Model_Entry::getInstanceByIdName($groupIdName);
			if ($this->_group == NULL) {
				Euso_Model_Log::push('group', 'member.'. $this->_getParam('action') .'.failed', 'Group not found',
					array('groupIdName' => $groupIdName));

				throw new Zend_Controller_Action_Exception('Group not found', 500);
			}
		} else {
			$fmsg = uniqid();
			$flashMessenger = $this->_helper->FlashMessenger;
			$flashMessenger->setNamespace($fmsg);
			$flashMessenger->addMessage('You need to be logged in to join or leave a group');
			$this->_redirect('/login?fmsg=' . $fmsg .'&return='. urlencode($_SERVER['REQUEST_URI']));
		}
	}

	public function joinAction()
	{
		if (Group_Model_Member::groupAddMember($this->_group->getId(), $this->_account->getId()) === TRUE) {

			Euso_Model_Log::push('group', 'member.join.succeeded', NULL,
				array('groupId' => $this->_group->getId(), 'groupIdName' => $this->_group->getIdName()));


			if (Kernel::getInstance()->isModuleActive('activity')) {
				Activity_Model_Logger::push('user', $accountId, 'joined',
					array(
						array('class'=>'group', 'id'=>$this->_group->getId(), 'role'=>'object')
					)
				);
			}

			$this->_redirect($this->_group->getUrl());
		}

		Euso_Model_Log::push('group', 'member.join.failed', 'System error',
			array('groupId' => $this->_group->getId(), 'groupIdName' => $this->_group->getIdName()));

		throw new Zend_Controller_Action_Exception('Cannot join group', 500);
	}

	public function partAction()
	{
		if (Group_Model_Member::groupRemoveMember($this->_group->getId(), $this->_account->getId()) === TRUE) {

			Euso_Model_Log::push('group', 'member.part.succeeded', NULL,
				array('groupId' => $this->_group->getId(), 'groupIdName' => $this->_group->getIdName()));

			$this->_redirect($this->_group->getUrl());
		}

		Euso_Model_Log::push('group', 'member.part.failed', 'System error',
			array('groupId' => $this->_group->getId(), 'groupIdName' => $this->_group->getIdName()));

		throw new Zend_Controller_Action_Exception('Cannot leave group', 500);
	}
}